package com.selune.online.ordering.system;

import com.selune.online.ordering.system.common.properties.CorsProperties;
import com.selune.online.ordering.system.common.properties.QiniuProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * SpringBoot方式系统启动类
 *
 * @author xiaoyp
 * @date 2020-02-20
 */

@SpringBootApplication
@EnableConfigurationProperties({CorsProperties.class, QiniuProperties.class})
public class OnlineOrderingSystemApplication {
	
	private final static Logger logger = LoggerFactory.getLogger(OnlineOrderingSystemApplication.class);
	
	@Autowired
	private CorsProperties corsProperties;
	
	public static void main(String[] args) {
		SpringApplication.run(OnlineOrderingSystemApplication.class, args);
		logger.info(OnlineOrderingSystemApplication.class.getSimpleName() + " is success!");
	}
	
	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		
		CorsProperties setting = corsProperties;
		//1.添加CORS配置信息
		CorsConfiguration config = new CorsConfiguration();
		//是否发送Cookie信息
		config.setAllowCredentials(setting.getCredentials());
		//放行哪些原始域
		config.setAllowedOrigins(setting.getOrigins());
		//放行哪些原始域(请求方式)
		config.setAllowedMethods(setting.getMethods());
		
		config.setMaxAge(3600L);
		//放行哪些原始域(头部信息)
		config.setAllowedHeaders(setting.getHeaders());
		//暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
		config.setExposedHeaders(setting.getHeaders());
		
		//2.添加映射路径
		source.registerCorsConfiguration(setting.getPattern(), config);
		
		//3.返回新的CorsFilter
		return new CorsFilter(source);
	}
	
}
